<?php

include_once('_path.php');

include_once(_CONST_LOCAL_INCLUDE_PATH."common.php");

include_once(_CONST_LOCAL_INCLUDE_PATH."database.class.php");
$database = new Database($db_vars);

if ($db_slave_vars['hostname'] != '') {
	$slave = new Database($db_slave_vars);
} else {
	$slave =& $database;
}

header('Content-type: application/json');
echo json_encode(search($_POST['q']));

function search($search) {
	global $slave;

	$min = 2; $max = 50;

	$search = normalize($search);
	$result = array();

	if (strlen($search) >= $min && strlen($search) <= $max) {
		$name_sql = "((1=1";
		foreach (explode(" ", $search) as $word) {
			if (strlen($word) > 1)
			$name_sql .= " AND i.series_name LIKE ".string_sql("%".$word."%");
		}

		$name_sql .= ") OR (";
		$name_sql .= " MATCH (i.series_name) AGAINST (".string_sql($search).")";
		$name_sql .= "))";

		$tmp = $slave->queryArray("SELECT i.series_name, i.series_code FROM index_series i WHERE $name_sql LIMIT 20", 600);
		foreach ($tmp as $item) {
			$result[] = array($item['series_name'], $item['series_code']);
		}
	}

	return $result;
}

function normalize ($s) {
	$s = preg_replace('/[^[:print:]\032-\126]/', ' ', $s);
	return trim(preg_replace('/ +/',' ', $s));
}

?>